package programs.statement;

import java.util.HashSet;
import java.util.Set;

import game.Ship;
import programs.expression.implementedClasses.Variable;
import programs.expression.superClasses.Expression;

public class Assignment extends BasicStatement {

	private Expression expressionToAssign;
	private Variable variable = null;
	private String variableName;
	
	public Assignment(Expression expressionToAssign, String variable) {
		this.expressionToAssign = expressionToAssign;
		this.variableName = variable;
	}

	@Override
	public void execute() {
			getVariable().setValue(getExpressionToAssign().getValue());
	}

	@Override
	public boolean isValidStatement() {
		return getExpressionToAssign().isValidExpression() && getVariable() != null &&
				getVariable().isValidExpression() && 
				getVariable().getReturnType() == getExpressionToAssign().getReturnType();
	}
	
	public Variable getVariable() {
		return this.variable;
	}
	
	public Expression getExpressionToAssign() {
		return this.expressionToAssign;
	}

	@Override
	public boolean containsAction() {
		return false;
	}
	
	@Override
	public void setExecuter(Ship executer) {
		super.setExecuter(executer);
		getExpressionToAssign().setExecuter(executer);
	}
	
	@Override
	public void assignGlobalVariable(Variable global) {
		if(global.getName().equals(this.variableName)) {
			this.variable = global;
		}
		this.expressionToAssign = this.expressionToAssign.assignGlobalVariable(global);
	}

	@Override
	public Set<Variable> getVariables() {
		Set<Variable> set = new HashSet<Variable>();
		set.add(getVariable());
		set.addAll(getExpressionToAssign().getVariables());
		return set;
	}
}
